<template>
  <el-container class="cop_friends">
    <el-main>
      <div class="card-list">
        <el-card shadow="never" class="selectCard searchColumn">
          <el-form label-position="right" label-width="6rem">
            <el-row :gutter="40">
              <el-col :span="6">
                <el-form-item label="群名称：">
                  <el-input v-model="searchParams.name" style="width: 240px;" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="群主名称：">
                  <el-input v-model="searchParams.ownerName" placeholder="请选择内容" :disabled="true">
                    <el-button slot="append" icon="el-icon-search" @click="empSelectDialogVisible = true" />
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="群标签：">
                  <el-select v-model="searchParams.tagsIds" multiple>
                    <el-option v-for="item in groupTagsList" :key="item.id" :value="item.id" :label="item.tagsName" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="建立时间：">
                  <el-date-picker
                    v-model="searchParams.buildTime"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    align="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="群状态：">
                  <el-select v-model="searchParams.type">
                    <el-option label="全部" value="" />
                    <el-option label="正常" :value="1" />
                    <el-option label="企业微信用户" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <SearchButton :default-params="searchParams" @refreshParams="refreshParams" @getList="getList1" />
          </el-form>
        </el-card>
        <el-card shadow="never" class="tableCard">
          <vxe-toolbar>
            <template v-slot:buttons>
              <el-dropdown placement="bottom-start" @command="getTag">
                <el-button type="primary" size="small">
                  打标签<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :disabled="checkList.length === 0" command="1">对选中的{{ checkedNum }}个群加标签</el-dropdown-item>
                  <el-dropdown-item command="2">对筛选出来的{{ total }}个群加标签</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-dropdown placement="bottom-start" @command="removeTag">
                <el-button type="primary" size="small">
                  去标签<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :disabled="checkList.length === 0" command="1">对选中的{{ checkedNum }}个群去标签</el-dropdown-item>
                  <el-dropdown-item command="2">对筛选出来的{{ total }}个群去标签</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <template v-slot:tools>
              <vxe-button class="tool-btn" type="text" size="small" icon="el-icon-download" @click="syncGroupListFromWx()">同步群</vxe-button>
              <vxe-button class="tool-btn" type="text" size="small" icon="el-icon-refresh" @click="getList1()">刷新</vxe-button>
            </template>
          </vxe-toolbar>
          <vxe-table
            ref="xTable"
            border
            resizable
            show-overflow
            highlight-hover-row
            :loading="loading"
            :auto-resize="true"
            :data="tableData"
            width
            max-height="500"
            :print-config="{}"
            header-align="center"
            :checkbox-config="{checkRowKeys: checkList, checkStrictly: false}"
            @checkbox-all="selectAll"
            @checkbox-change="selectChangeEvent"
          >
            <vxe-table-column type="checkbox" width="35" />
            <vxe-table-column field="name" width="180" title="群名称" />
            <vxe-table-column field="ownerName" min-width="100" align="left" title="群主" />
            <vxe-table-column field="groupTagsStr" width="250" align="left" title="群标签" />
            <vxe-table-column field="sumGroupFriendsNum" width="120" align="right" title="群内客户数" />
            <vxe-table-column field="todayJoinNum" min-width="120" align="right" title="今日入群数" />
            <vxe-table-column field="todayOutNum" min-width="120" align="right" title="今日退群数" />
            <vxe-table-column field="buildTime" width="180" align="left" title="建立时间" />
            <vxe-table-column field="statusDesc" width="120" align="center" title="状态" />
            <vxe-table-column title="操作" fixed="right" align="center" width="150" slots="default">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="openDialog(scope.row.id, true)">详情</el-button>
              </template>
            </vxe-table-column>
          </vxe-table>
          <vxe-pager
            :current-page.sync="tableCurrentPage"
            :page-size.sync="pageSize"
            :total="total"
            :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            @page-change="getList()"
          />
        </el-card>
      </div>
    </el-main>
    <el-dialog :close-on-click-modal="false" :modal="false" :visible.sync="dialogVisible" title="信息查询">
      <el-form :model="params" label-width="7rem">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="群名称：" prop="name">
              <el-input v-model="params.name" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="群主：" prop="ownerName">
              <el-input v-model="params.ownerName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建立时间：" prop="buildTime">
              <el-input v-model="params.buildTime" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：" prop="statusDesc">
              <el-input v-model="params.statusDesc" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="群标签：" prop="groupTagsStr">
              <el-input v-model="params.groupTagsStr" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="empSelectDialogVisible" width="60%" title="选择" :close-on-click-modal="false" :visible.sync="empSelectDialogVisible" append-to-body>
      <div class="card-list">
        <el-card shadow="never" class="selectCard searchColumn">
          <el-form ref="ruleForm" label-position="right" :model="selectEmployeeParams" label-width="6rem">
            <el-row :gutter="40">
              <el-col :span="10">
                <el-form-item label="员工姓名：" prop="employeeNameCn">
                  <el-input v-model="selectEmployeeParams.employeeNameCn" style="width: 240px;" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <SearchButton :default-params="chooseEmployeeParams" @refreshParams="refreshEmployeeParams" @getList="getEmployeeList1" />
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card shadow="never" class="tableCard">
          <vxe-toolbar :refresh="{query: getEmployeeList}" />
          <vxe-table
            ref="listEmployee"
            border
            resizable
            highlight-hover-row
            :auto-resize="true"
            :data="employeeList"
            width
            max-height="300"
            highlight-current-row
            :radio-config="{highlight: true}"
            text-algin="center"
          >
            <vxe-table-column type="radio" width="80" />
            <vxe-table-column min-width="220" field="employeeNameCn" title="员工姓名" />
            <vxe-table-column field="mainDepartmentNameCn" title="所属部门" min-width="160" />
            <vxe-table-column width="150" field="mobile" title="联系电话" />
            <vxe-table-column field="statusDesc" title="员工状态" min-width="120" />
          </vxe-table>
          <vxe-pager
            :current-page.sync="selectEmployeeParams.pageNum"
            :page-size.sync="selectEmployeeParams.pageSize"
            :total="employeeTotal"
            :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            @page-change="getEmployeeList"
          />
        </el-card>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="empSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="clickEmployeeSure">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="tagsDialogVisible" title="请选择要打的标签" :close-on-click-modal="false" :visible.sync="tagsDialogVisible">
      <el-form>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标签">
              <el-select v-model="groupTagsIds" multiple filterable placeholder="请选择">
                <el-option v-for="item in groupTagsList" :key="item.id" :label="item.tagsName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tagsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickTagsSure">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import SearchButton from '@/components/SearchButton'
import { syncGroupListFromWx, getGroupTagsList, getGroupPageList, viewGroup, changeTagsBatch } from '@/api/cop/group'
import { getEmployeePageList } from '@/api/cop/contact'
export default {
  components: {
    SearchButton
  },
  data() {
    return {
      dialogVisible: false,
      empSelectDialogVisible: false,
      tagsDialogVisible: false,
      selectEmployeeParams: {},
      employeeTotal: 0,
      employeeList: [],
      checkList: [],
      checked: false,
      checkedNum: 0,
      searchParams: {
        tagsIds: [],
        name: '',
        ownerId: '', // 所在地区
        ownerName: '', // 所在地区
        type: '',
        buildTime: ''
      },
      params: {},
      tableData: [],
      tableCurrentPage: 1,
      pageSize: 20,
      total: 0,
      selectId: '',
      loading: false,
      nowUserId: '',
      flag: false,
      groupTagsIds: [],
      tagType: '1', // 1选中 2全选
      groupTagsList: [],
      pickerOptions: this.$store.getters.pickerOptions
    }
  },
  mounted() {
    this.getList()
    this.getGroupTagsList()
  },
  methods: {
    syncGroupListFromWx() {
      this.$confirm('确定要从企业微信同步群列表, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        syncGroupListFromWx().then(res => {
          if (res) {
            this.$message.info('正在从企业微信同步群列表，请稍候刷新！')
            this.$nextTick(() => {
              this.getList()
            })
          }
        })
      }).catch(() => {
        this.$message.info('取消操作')
      })
    },
    getGroupTagsList() {
      getGroupTagsList({ status: 1 }).then(res => {
        this.groupTagsList = res
      })
    },
    getEmployeeList() {
      getEmployeePageList(this.selectEmployeeParams).then(res => {
        this.employeeList = res.records
        this.total = res.total
      })
    },
    getEmployeeList1() {
      this.selectEmployeeParams.pageNum = 1
      this.getEmployeeList()
    },
    refreshEmployeeParams(params) {
      this.selectEmployeeParams = params
    },
    clickEmployeeSure() {
      if (this.$refs.listEmployee.getRadioRecord()) {
        const selectedRow = JSON.parse(JSON.stringify(this.$refs.listEmployee.getRadioRecord()))
        this.searchParams.ownerName = selectedRow.employeeNameCn
        this.searchParams.ownerId = selectedRow.id
        this.empSelectDialogVisible = false
      }
    },
    // 状态
    changeState(scope) {
    },
    // 详情
    openDialog(id, bool) {
      viewGroup({ id })
        .then(response => {
          if (response) {
            this.params = response
            this.dialogVisible = true
          }
        }).catch((err) => {
          this.$message.err(err.msg)
        })
    },

    refreshParams(params) {
      this.searchParams = params
    },
    getList1() {
      this.searchParams.tableCurrentPage = 1
      if (this.searchParams.buildTime && this.searchParams.buildTime.length > 0) {
        this.searchParams.buildTimeBegin = this.searchParams.buildTime[0] + ' 00:00:00'
        this.searchParams.buildTimeEnd = this.searchParams.buildTime[1] + ' 23:59:59'
      }
      this.getList()
    },
    // 列表
    getList() {
      getGroupPageList({
        pageNum: this.tableCurrentPage,
        pageSize: this.pageSize,
        ... this.searchParams
      }).then(response => {
        if (response) {
          this.tableData = response.records
          this.total = response.total
          this.checkList = []
          this.checkedNum = 0
        }
      }).catch((err) => {
        this.$message.err(err.msg)
      })
    },
    addTag() {
      this.$refs.xTable.getCheckboxRecords()
    },
    // 1选中 2全选
    getTag(i) {
      this.tagType = i
      this.groupTagsIds = []
      this.userIds = i === '1' ? this.getCheckList : []
      this.tagsDialogVisible = true
    },
    selectAll(e) {
      if (e.checked) {
        this.checkList.push(...e.records.map(item => item.id))
        this.checkList = Array.from(new Set(this.checkList))
        this.checkedNum = this.checkList.length
      } else {
        const arr = this.list.map(item => item.id)
        const arr1 = []
        this.checkList.forEach((item, index) => {
          arr.forEach(it => {
            if (item === it) {
              arr1.push(index)
            }
          })
        })
        arr1.reverse().forEach(item => {
          this.checkList.splice(item, 1)
        })
      }
      this.checkedNum = this.checkList.length
    },
    selectChangeEvent(row) {
      let i = -1
      this.checkList.forEach((item, index) => {
        if (item === row.row.id) {
          i = index
        }
      })
      if (i === -1) {
        this.checkList.push(row.row.id)
      } else {
        this.checkList.splice(i, 1)
      }
      this.checkedNum = this.checkList.length
    },
    removeTag(i) {
      this.$confirm('确定要对选中的客户去除标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        if (this.searchParams.tagsIds === null || this.searchParams.tagsIds.length <= 0) {
          this.$message.error('请在搜索条件中选择要取消的标签！')
        } else {
          this.handleFriendsTags(i, '2')
        }
      }).catch(() => {
        this.$message.info('取消操作')
      })
    },
    clickTagsSure() {
      if (this.groupTagsIds.length === 0) {
        this.$message.error('请选择标签')
      } else {
        this.handleFriendsTags(this.tagType, '1')
      }
    },
    handleFriendsTags(type, addOrLess) {
      changeTagsBatch({
        type: type,
        addOrLess: addOrLess,
        condition: type === '2' ? this.searchParams : {},
        tagsIds: addOrLess === '1' ? this.groupTagsIds : this.searchParams.tagsIds,
        groupIds: this.checkList
      }).then(res => {
        if (addOrLess === '1') {
          this.$message.success('打标签成功！')
        } else {
          this.$message.success('减标签成功！')
        }
        this.tagsDialogVisible = false
        this.getList()
      })
    }
  }
}
</script>

<style lang="scss">
.cop_friends {
  .card-list {
    width: 100%;
  }
  .headerIcon {
    width: 40px;
    height: 40px;
  }
}

</style>
